package com.wzh.ojbackendserviceclient.service;

import com.wzh.ojCommon.common.ErrorCode;
import com.wzh.ojCommon.constant.SystemNameConstant;
import com.wzh.ojCommon.constant.UserConstant;
import com.wzh.ojCommon.exception.BusinessException;
import com.wzh.ojModel.model.entity.User;
import com.wzh.ojModel.model.enums.UserRoleEnum;
import com.wzh.ojModel.model.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.List;

/**
 * @author wzh
 */
@FeignClient(name = SystemNameConstant.OJ_BACKEND_USER_SERVICE,path = "/api/user/inner")
public interface UserFeignClient {
    /**
     *获取当前登陆的用户
     * @param request
     * @return User
     */
    default User getLoginUser(HttpServletRequest request){
        User user =(User) request.getSession().getAttribute(UserConstant.USER_LOGIN_state);
        if (user==null||user.getId()==null){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
//        通过数据库查询可以获取当前用户的最新信息
//        此处可以通过缓存进行优化,提高性能
        return user;
    }


    /**
     * 判断用户是否是管理员
     * @param user 用户信息
     * @return boolean
     */
  default boolean isAdmin(User user){
      return user != null && UserRoleEnum.ADMIN.getValue().equals(user.getUserRole());
  }


    /**
     * @param user 用户信息
     * @return 用户脱敏信息
     */
    default UserVO getUserVO(User user){
        if (user == null) {
            return null;
        }
        UserVO userVO=new UserVO();
        BeanUtils.copyProperties(user,userVO);
        return userVO;
    }


    /**
     * 根据 id 获取用户列表
     * @param idList
     * @return
     */
    @GetMapping("/get/ids")
    List<User> listByIds(@RequestParam("idList") Collection<Long> idList);

    /**
     * 根据用户的id直接获取用户的信息
     * @param userId
     * @return User
     */
    @GetMapping("/get/id")
    User getById(@RequestParam("userId") long userId);


}
